<?php

/**
 * Class ImpQuest.php
 *
 * Class that deals with the storage/management of questions inserted by groups
 * in the diad stage
 *
 * @author Jose Oliveira <jafo@ua.pt> 2012
 */

class ImpQuest{

	private $ImpQuestID;
	private $question;
	Private $projectID;
	private $groupID;
	private $dateHour;
	private $edited;

	/**
	 * 
	 * @param string $question
	 * @param integer $projectID
	 * @param integer $groupID
	 */
	function __construct($question, $projectID, $groupID){

		if(isset($question) && isset($projectID) && isset($groupID)){
			$this->question=$question;
			$this->projectID=$projectID;
			$this->groupID=$groupID;
		}
	}

	/**
	 * Method that stores an question on the table ImpQuest case this is 
	 * not an edtition to a previously made question​​.
	 * return 0: storing of the question has failed
	 * return 1: improved question stored with success
	 * return 2: the question has been previously entered by the group
	 * @throws Exception
	 * @return integer
	 * 
	 */
	
	public function addImpQuest(){

		if($this->validQuestion($this->question, $this->groupID, $this->projectID)){
			$date=date("Y-m-d H:i:s");

			$conn=new ConnDBUser();
			$conn->connect();    //liga à base de dados com privilégios de utilizador web

			$quest=mysql_real_escape_string($this->question);

			$result=mysql_query("insert into impQuest(impQuest, edited, dateHour, groupID, projectID, state)
			values('$quest', 0, '$date', '" . $this->groupID . "', '" . $this->projectID . "', 1)");

			if(!$result){
				throw new Exception("Lamentamos mas ocorreu um erro: " . mysql_error());
			}

			try{
				$conn->disconnect($result);
				return 1;
			}catch(Exception $e){
				$e->getMessage();
			}

		}else{
			return 2;
		}
		
		return 0;
	}


	/**
	 * Method that receives a improved question ID and returns the respective question
	 * @param integer $impQuestID
	 * @throws Exception
	 * @return string
	 */
	public function getQuestByID($impQuestID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select impQuest from impQuest where impQuestID=$impQuestID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao aquirir este elemento");
		}

		try{

			$registo=mysql_fetch_array($result);
			$conn->disconnect($result);
			return $registo['impQuest'];

		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that verifies if this question has not yet been entered by this group 
	 * @param string $question
	 * @param integer $groupID
	 * @param integer $projectID
	 * @throws Exception
	 * @return bool
	 */
	private function validQuestion($question, $groupID, $projectID){
		/*
		 * Se a questão que o utilizador tentar inserir for válida, o método retorna true; caso contrário, retorna false;
		 */

		$conn=new ConnDBUser();
		$conn->connect();

		$quest=mysql_real_escape_string($question);

		$result=mysql_query("select * from impQuest where impQuest='$quest' and projectID='$projectID' and groupID='$groupID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);
			$conn->disconnect($result);
			if($num==0){
				//significa que este grupo nunca inseriu uma questão igual a esta neste projecto e podemos retornar true;
				return true;
			}else{
				return false;
			}
		}catch(Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * Method that update de field "edited" of this question to "1"
	 * @param integer $questionID
	 * @throws Exception
	 * @return bool
	 */
	public function updateToEdited($questionID){
		/*
		 * Método que recebendo o ID de uma questão refinada, atualiza o seu estado para edited=1;
		 */

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("update impQuest set edited=1 where impQuestID=$questionID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro: " . mysql_error());
		}

		try{
			$conn->disconnect($result);
			return true;
		}catch (Exception $e){
			$e->getMessage();
		}

		$conn->disconnect($result);
		return false;
	}

	/**
	 * Method that returns the IDs of all questions that have been edited
	 * from a certain group. 
	 * Note: when we print the questions of the group, we should only print the
	 * latest update of each question
	 * @param integer $projectID
	 * @param integer $groupID
	 * @throws Exception
	 * @return array
	 * Returns array with all IDs of questions that have been edited from a certain group
	 */
	public function edQuestIDs($projectID, $groupID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select impQuestID from impQuest where edited=1 and projectID=$projectID and groupID=$groupID and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num==0){
				$conn->disconnect($result);
				return 0;           //se não houverem questões editadas, não retornamos nada
			}else{
				$ids=array();

				while($registo=mysql_fetch_array($result)){
					$temp=$registo['impQuestID'];       //criação de array uni-dimensional com os ID's das questões que sofreram edição
					array_push($ids, $temp);
				}

				$conn->disconnect($result);
				return $ids;
			}
		}catch(Exception $e){
			echo $e->getMessage();
		}

		$conn->disconnect($result);
		return 0;
	}



	/**
	 * Method that returns the info about all questions of a group that haven't been edited
	 * @param integer $groupID
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getNoEditedQuestInfo($groupID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select impQuestID, impQuest, dateHour, projectID from impQuest where groupID=$groupID and projectID=$projectID and edited=0 and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num>0){
				$info=array();
				while($registo=mysql_fetch_array($result)){
					array_push($info, $registo);
				}

					
				$conn->disconnect($result);
				return $info;
			}else{
				$conn->disconnect($result);
				return '';
			}

		}catch(Exception $e){
			echo $e->getMessage();
		}

	}

	/**
	 * Returns the number of questions of active (not deleted by users) inserted by a certain group, 
	 * in a certain project, in the diad stage
	 * @param unknown_type $groupID
	 * @throws Exception
	 */
	public function getNumberOfQuestions($groupID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select impQuestID from impQuest where groupID='$groupID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);
			$conn->disconnect($result);
			return $num;

		}catch(Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * Method that returns the IDs of all questions that have been edited
	 * from a certain group. 
	 * Note: when we print the questions of the group, we should only print the
	 * latest update of each question
	 * Returns array with all IDs of questions that have been edited from a certain group
	 * @param integer $groupID
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function editedQuestionsIDs($groupID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select impQuestID from impQuest where edited=1 and projectID='$projectID' and groupID='$groupID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num==0){
				$conn->disconnect($result);
				return 0;           //se não houverem questões editadas, não retornamos nada
			}else{
				$ids=array();

				while($registo=mysql_fetch_array($result)){
					$temp=$registo['impQuestID'];       //criação de array uni-dimensional com os ID's das questões que sofreram edição
					array_push($ids, $temp);
				}

				$conn->disconnect($result);
				return $ids;
			}
		}catch(Exception $e){
			echo $e->getMessage();
		}

		$conn->disconnect($result);
		return 0;
	}

	/**
	 * Method that returns the info about all questions that haven't been edited
	 * This is used in the stage of question discussion
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getAllNoEditedFromProject($projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from impQuest where edited='0' and projectID='$projectID' order by dateHour asc");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num>0){
				$info=array();
				while($registo=mysql_fetch_array($result)){
					array_push($info, $registo);
				}

					
				$conn->disconnect($result);
				return $info;
			}else{
				$conn->disconnect($result);
				return '';
			}

		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method used to unset a certain question. Used when a group wants to delete a question
	 * @param integer $impQuestID
	 * @throws Exception
	 * @return bool
	 */
	public function unsetImpQuest($impQuestID){
		
		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("update impQuest set state=0 where impQuestID=$impQuestID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$conn->disconnect($result);
			return true;
		}catch(Exception $e){
			$e->getMessage();
		}
	}

	
	/**
	 * Method that returns the IDs of all questions that have been edited
	 * This is used in the stage of question discussion
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getAllEditedIDSFromProject($projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select impQuestID, groupID from impQuest where edited='1' and projectID='$projectID' order by dateHour asc");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

				$info=array();
				while($registo=mysql_fetch_array($result)){
					array_push($info, $registo);
				}

					
				$conn->disconnect($result);
				return $info;
			
		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that returns an array with info properly formatted for the project administrator, with questions, 
	 * edited and unedited from each group in a certain project
	 * @param integer $groupID
	 * @param integer $projectID
	 * @throws Exception
	 */
	public function preparedArrayForAdmin($groupID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from impQuest where groupID=$groupID and projectID=$projectID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao obter as questões do grupo");
		}

		try{

			$firstArray=array();
			while($registo=mysql_fetch_array($result)){
				array_push($firstArray, $registo);
			}

			$conn->disconnect($result);

			//agora que já temos um array com todas as funções, vamos passá-lo por um método privado, que trata da verificação da existencia de edições
			$arrayFinal=$this->tuneAdminArray($firstArray);
			return $arrayFinal;

		}catch(Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * Method that get a question ID and returns the group ID that saved that question
	 * @param integer $questionID
	 * @throws Exception
	 * @return integer
	 */
	public function getGroupID($questionID){
		
		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select groupID from impQuest where impQuestID=$questionID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao obter as questões do grupo");
		}

		try{

			$registo=mysql_fetch_array($result);
	
			$conn->disconnect($result);
			//agora que já temos um array com todas as funções, vamos passá-lo por um método privado, que trata da verificação da existencia de edições
			return $registo['groupID'];

		}catch(Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * Method that completes the array of the method preparedArrayForAdmin
	 * @param array $array
	 * @return array
	 */
	private function tuneAdminArray($array){
		/*
		 * Método privado que acrescenta ao array das perguntas dos grupos as respetivas edições
		 */

		$cleanArray=array();

		for($i=0; $i<count($array); $i++){

			if($array[$i]['edited']==1){

				//se for editado, vamos  buscar todas as versões:
				$edImpQuest=new EdImpQuest('', '');
				$tempArray=$edImpQuest->showPreviousVersionsOfQuestion($array[$i]['impQuestID']);
				unset($edImpQuest);
				$cleanArray=array_merge($cleanArray, $tempArray);
			}else{
				$tempArray=array("question" => $array[$i]['impQuest'], "dateHour" => $array[$i]['dateHour'], "state" => $array[$i]['state'], "groupID" => $array[$i]['groupID'], "edited" => 0, "instance" => 0, "bold" => 1, "origQuestID" => $array[$i]['impQuestID']);
				array_push($cleanArray, $tempArray);
			}

		}

		return $cleanArray;
	}

}
?>